<template>
  <div class="payment-box">
    <Hander></Hander>

    <div class="content-box">
      <div class="box-bg">
        <UserHand />

        <div class="bg-content">
          <div class="content-title">
            <div class="title-icon"></div>
            ( {{ devData.name }}){{ devData.location }}
          </div>
        </div>
        <div class="bg-content" style="justify-content: flex-end">
          <van-button type="warning" size="mini" @click="bxpage">
            报损
          </van-button>
        </div>

        <!-- <div class="bg-white rounded-xl flex-col items-center">
          <div class="mb-4">
            <van-field
              style="background: #f3f5f9; border-radius: 0.33rem"
              class="mt-4"
              border
              v-model="inputMinutes"
              type="digit"
              placeholder="请输入需要使用的分钟数"
              @blur="handleMoney"
            />
          </div>
        </div> -->
        <van-row class="flex justify-between">
          <van-col v-for="item in moneyArr" :key="item" span="7" class="mt-2">
            <div
              :class="money == item.fee ? 'bg2' : 'bg1'"
              class="py-4 text-center w-full"
              style="border-radius: 6px"
              @click="setTimer(item)"
            >
              {{ item.minutes }}分钟
            </div>
          </van-col>
        </van-row>

        <div class="bg-ts">
          <span class="start">*</span>您选择的{{
            inputMinutes ? inputMinutes : 0
          }}分钟需要付费{{ money ? money : 0 }}金额！
        </div>

        <van-button
          style="margin-bottom: 40px"
          block
          round
          color="#47BC91"
          @click="submit"
          :disabled="zfBUT"
          :loading="userCode ? false : true"
          >付费使用
        </van-button>
        <!-- 
        <div class="bg-content">
          <div class="content-title">
            <div class="title-icon"></div>
            注意事项
          </div>
        </div>
        <div class="zysx">
          <div v-html="valueHtml"></div>
        </div> -->
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, onMounted, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import { showDialog } from "vant";

import Hander from "@/components/hander.vue";
import UserHand from "@/components/userHand.vue";

import { useCounterStore } from "@/stores/counter"; // 根据你的实际路径调整

import {
  createOrder,
  generate,
  baseUrl,
  blowdurationsfindAll,
  devicesfindById,
  announcementsfindAll,
  getOPenIdByAccount,
} from "@/api/index.js";

const route = useRoute();
const router = useRouter();

// 获取 store 实例
const counterStore = useCounterStore();

const userInfo = computed(() => counterStore.userInfo);
let waterUserInfo = ref({});
const loading = ref(false);
let userCode = ref(null);

//输入分钟数
let inputMinutes = ref("");

const money = ref(0);
const moneyArr = ref([]);

//输入框
const handleMoney = () => {};
//选择时间
const setTimer = (item) => {
  money.value = item.fee;
  inputMinutes.value = item.minutes;
};

const submit = async () => {
  if (!money.value) {
    return showToast({
      message: "金额不能为空",
      duration: 2000,
    });
  }

  // if (!userInfo.value) {
  //   showToastReg();
  //   return;
  // }
  // if (!waterUserInfo.value) {
  //   showToastRegHot();
  //   return;
  // }
  // 注释白名单
  // let res = await validate({studentId:userInfo.value.number});
  // if (res.code != 200) {
  //   showToast({
  //     message: res.message ? res.message : '充值失败，请确认用户信息是否完整！',
  //     duration: 2000,
  //   });
  //   return;
  // }
  let data = {
    orderAmount: money.value,
    // phoneNumber: userInfo.value.phone || "",
    // account: userInfo.value.account || "",
    // studentId: userInfo.value.account || "",
    // waterCardNumber: waterUserInfo.value.carPhysicalld || "",
    deviceId: route.query.id,
    fee: money.value,
    imei: devData.value.imei,
    manufacturer: devData.value.manufacturer,
    minutes: inputMinutes.value,
    userAccount: userInfo.value.account || "",
    userPhone: userInfo.value.phone || "",
    userType: userInfo.value.userType || "",
    username: userInfo.value.name || "",
  };

  loading.value = true;
  function generateRandomString(length) {
    const characters =
      "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    let result = "";
    const charactersLength = characters.length;
    for (let i = 0; i < length; i++) {
      result += characters.charAt(Math.floor(Math.random() * charactersLength));
    }
    return result;
  }
  createOrder(data).then(async (rs) => {
    if (rs.code == 200 && rs.data) {
      // waterUserInfo.value = rs.data;
      let d = rs.data;
      loading.value = false;
      // d.studentId = 'yktcs001';
      let myapp_id = "101497";
      let subject = "共享吹风机";
      let t = new Date().getTime();
      let nonce_str = generateRandomString(10);
      let sub_openid = userCode.value;
      // let notify_address = 'https://42984154fw.vicp.fun/payment/notify';
      let notify_address = baseUrl + "/payment/notify";
      // let notify_address = 'https://42984154fw.vicp.fun/payment/notify'
      let redirect_url = "https://wsh.swpu.edu.cn/shareh5/";
      // let redirect_url = 'https://saas-wap.sicnu.edu.cn/';
      let json = {
        total_amount: d.fee * 100,
        out_trade_no: d.businessOrderNo,
        nonce_str: nonce_str,
        sub_openid: sub_openid,
        myapp_id: myapp_id,
        time_stamp: t,
        subject: subject,
        sign: null,
        notify_address: notify_address,
        redirect_url: redirect_url,
      };
      let res = await generate(json);
      if (res.code != 200) {
        showToast({
          message: "请求失败，请重试！",
          duration: 2000,
        });
        return;
      }
      // console.log(rs,'订单');

      // console.log(res, "返回的数据");
      // return
      let sign = res.data.sign;

      // let subject = "共享吹风机";
      // let href = `https://dev-sicnu-cashier-wap.goliveplus.cn/cashPage?myapp_id=${myapp_id}&out_trade_no=${d.businessOrderNo}&total_amount=${d.orderAmount * 100}&nonce_str=${nonce_str}&sign=${sign}&time_stamp=${t}&auth_code=${d.studentId}&notify_address=${notify_address}&redirect_url=${redirect_url}&sub_openid=${sub_openid}&subject=${subject}&trade_type=jsapi`
      let href = `https://cashier.wap.goliveplus.cn/cashPage?myapp_id=${myapp_id}&out_trade_no=${
        d.businessOrderNo
      }&total_amount=${
        d.fee * 100
      }&nonce_str=${nonce_str}&sign=${sign}&time_stamp=${t}&notify_address=${notify_address}&sub_openid=${sub_openid}&redirect_url=${redirect_url}&subject=${subject}`;

      // https://service.payment.goliveplus.cn

      console.log(href);
      // let href = `https://dev-sicnu-cashier-wap.goliveplus.cn/cashPage?myapp_id=${myapp_id}&out_trade_no=${d.businessOrderNo}&total_amount=${d.orderAmount}&nonce_str=${nonce_str}&sign=${sign}&time_stamp=${t}&auth_code=${d.studentId}&notify_address=${notify_address}&redirect_url=${redirect_url}`
      // let href = `https://erp-wap.sicnu.edu.cn/cashPage?myapp_id=${myapp_id}&out_trade_no=${d.businessOrderNo}&total_amount=${d.orderAmount}&nonce_str=${nonce_str}&sign=${sign}&time_stamp=${t}&auth_code=${d.studentId}&notify_address=${notify_address}&redirect_url=${redirect_url}`
      window.location.href = href;

      return;
    }
    loading.value = false;
  });
  // }
};

//获取时间选择
const getTime = async (deviceType) => {
  try {
    let res = await blowdurationsfindAll({
      page: 1,
      size: 10,
      deviceType: deviceType,
    });
    moneyArr.value = res.data.content;
    moneyArr.value.sort((a, b) => a.minutes - b.minutes);
  } catch (error) {}
};

//获取设备详情
let zfBUT = ref(false); //按钮是否禁用
let devData = ref({});
const getdevicesfindById = async (deviceId) => {
  try {
    let res = await devicesfindById({
      deviceId,
    });
    devData.value = res.data;
    getTime(devData.value.deviceType);

    //判断设备是否维修中
    if (devData.value.status != "NORMAL") {
      showDialog({
        message: "设备正在维修，请跟换其他设备。",
      }).then(() => {
        router.go(-1);
      });
    } else {
      //判断时间段 useTime 为空 则全天可用
      if (devData.value.useTime) {
        let flge = isInTimeRanges(devData.value.useTime);
        if (!flge) {
          zfBUT.value = true;
          showDialog({
            message: `您选择的设备不在运营时间段，该设备运营时间段为${devData.value.useTime}，请选择其他设备使用。`,
          }).then(() => {});
        }
      }
    }
  } catch (error) {}
};

// // 获取注意事项
// let zyList = ref([]);
// let valueHtml = ref("");
// const getannouncementsfindAll = async () => {
//   try {
//     let res = await announcementsfindAll({
//       page: 1,
//       size: 1,
//     });
//     //如果获取到数据
//     zyList.value = res.data.content;

//     if (zyList.value.length > 0) {
//       valueHtml.value = zyList.value[0].content;
//     }
//   } catch (error) {}
// };

//判断当前时间是不是在范围内
const isInTimeRanges = (timeRanges) => {
  // 获取当前时间的小时和分钟，并转换为分钟数
  const now = new Date();
  const currentMinutes = now.getHours() * 60 + now.getMinutes();

  // 分割多个时间段
  const ranges = timeRanges.split("|");

  for (const range of ranges) {
    // 分割单个时间段的开始和结束时间
    const [startStr, endStr] = range.split("-");

    // 将时间字符串转换为分钟数
    const startMinutes = convertToMinutes(startStr);
    const endMinutes = convertToMinutes(endStr);

    // 处理跨夜时段（如 23:00 到次日 01:00）
    if (startMinutes < endMinutes) {
      // 非跨夜时段
      if (currentMinutes >= startMinutes && currentMinutes < endMinutes) {
        return true;
      }
    } else {
      // 跨夜时段（拆分为两段判断）
      if (currentMinutes >= startMinutes || currentMinutes < endMinutes) {
        return true;
      }
    }
  }

  return false;
};

// 辅助函数：将 "HH:mm" 格式的时间转换为分钟数
const convertToMinutes = (timeStr) => {
  const [hours, minutes] = timeStr.split(":").map(Number);
  return hours * 60 + minutes;
};

//保修
const bxpage = () => {
  router.push({
    path: "/reportLoss",
    query: { id: devData.value.id }, // 传递参数 id=10
  });
};

const showToastAuth = () => {
  showConfirmDialog({
    title: "提示",
    "show-cancel-button": false,
    message:
      "未获取到用户信息，请进入西南石油大学后勤服务大厅，点击吹风/插座应用进行授权使用。",
  })
    .then(() => {
      // 注册
      window.location.href = "https://hqfw.swpu.edu.cn/appLogin";
    })
    .catch(() => {
      // on cancel
    });
};

//获取openid
const getOPenId = async () => {
  try {
    let res = await getOPenIdByAccount({
      account: userInfo.value.account,
    });

    if (res.code == 200) {
      let myData = JSON.parse(res.data);
      if (myData.data && myData.data.length > 0) {
        userCode.value = myData.data[0].openId;
      }
    }

    if (!userCode.value) {
      showToastAuth();
    }
  } catch (error) {
    showToastAuth();
  }
};

onMounted(() => {
  // getannouncementsfindAll();

  //判断用户是否登录
  const { name, account, userType, phone, timeStamp } = userInfo.value;
  if (account && name) {
    getOPenId();
  } else {
    showToastAuth();
  }

  if (route.query.id) {
    getdevicesfindById(route.query.id);
  }
});
</script>
<style scoped lang="scss">
.bg1 {
  background: #f3f5f9;
  color: #555555;
}

.bg2 {
  background: #ebfff8;
  color: #47bc91;
}

.payment-box {
  width: 100%;
  height: 100vh;
  background: #47bc91;

  .content-box {
    width: 100%;
    height: calc(100vh - 120px);
    box-sizing: border-box;
    padding: 0 12px;
    position: relative;
    z-index: 1;

    .box-bg {
      width: 100%;
      background: #ffffff;
      border-radius: 14px;
      height: 100%;

      box-sizing: border-box;
      padding: 0 12px;
      overflow-y: auto;

      .bg-content {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 20px;
        .content-title {
          display: flex;
          align-items: center;

          font-weight: bold;
          font-size: 16px;
          color: #151515;

          .title-icon {
            width: 4px;
            height: 21px;
            background: #47bc91;
            border-radius: 2px;
            margin-right: 5px;
          }
        }

        .content-btn {
          box-sizing: border-box;
          padding: 5px 9px;
          background-color: #ffe6e6;

          font-weight: 400;
          font-size: 12px;
          color: #f30f0f;

          border: 1px solid #ff0c0c;
        }
      }

      .bg-ts {
        margin-top: 10px;
        font-size: 14px;
        color: #191919;
        margin-bottom: 31px;
        .start {
          color: red;
        }
      }

      .zysx {
        height: 20vh;
        overflow-y: auto;
        margin-top: 15px;
        color: #858585;
      }
    }
  }
}
</style>
